<template>
	<div class="login-view" style="">
		<div class="back_box">
			<img class="img" src="../../public/login_back.png" alt="">
			<div class="version_box">
				{{ 'version:' + appVersion }}
			</div>
		</div>
		<div class="login-content drag-box" v-show="pageType == 'login'">
			<dragBar login></dragBar>
			<div class="language_box drag-box-none">
				<el-select class="select" v-model="language" placeholder="语言" width="100px" @change="changeLanguage"
					style="background-color: none;">
					<el-option v-for="item in languageList" :key="item.value" :label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</div>

			<div class="login-brand">
				<img class="logo" src="../../public/logo.png" />
				<!-- <div>登录Shannon</div> -->
			</div>

			<el-form class="login-form drag-box-none" :model="loginForm" status-icon :rules="rules" ref="loginForm"
				@keyup.enter.native="submitForm('loginForm')">
				<div class="loginType">
					<div class="item" v-if="false">
						{{ $t('手机号注册') }}
					</div>
					<div class="item" :class="{ on: loginType == '2' }">
						{{ $t('邮箱登录') }}
					</div>
				</div>

				<el-form-item label="终端" prop="terminal" v-show="false">
					<el-input type="terminal" v-model="loginForm.terminal" autocomplete="off"></el-input>
				</el-form-item>

				<el-form-item label="" prop="phone" v-if="loginMethod == 'password'">
					<el-input type="phone" v-model="loginForm.phone" autocomplete="off"
						:placeholder="$t('用户名')"></el-input>
				</el-form-item>

				<el-form-item label="" prop="email" v-else>
					<el-input type="email" v-model="loginForm.email" autocomplete="off" :placeholder="$t('邮箱')">
						<el-button slot="append" @click="code">{{ $t(text) }}</el-button>
					</el-input>
				</el-form-item>

				<el-form-item label="" prop="captcha" v-if="loginMethod == 'code'">
					<el-input type="captcha" v-model="loginForm.captcha" autocomplete="off"
						:placeholder="$t('验证码')"></el-input>
				</el-form-item>

				<el-form-item label="" prop="password" v-if="loginMethod == 'password'">
					<el-input type="password" v-model="loginForm.password" autocomplete="off"
						:placeholder="$t('密码')"></el-input>
				</el-form-item>

				<el-form-item label="">
					<el-checkbox v-model="remember">{{ $t('记住密码') }}</el-checkbox>

				</el-form-item>

				<el-form-item class="btn_box">
					<el-button type="primary fullbtn" @click="submitForm('loginForm')">{{ $t('登录') }}</el-button>
					<!-- <el-button @click="resetForm('loginForm')">清空</el-button> -->
				</el-form-item>
				<div class="register">
					<!-- <router-link to="/register">没有账号,前往注册</router-link> -->
				</div>

				<div class="changeLoginMethod">
					<div class="item" v-if="loginMethod == 'password'" @click="loginMethod = 'code'">
						{{ $t('验证码登录') }}
					</div>
					<div class="item" v-else @click="loginMethod = 'password'">
						{{ $t('密码登录') }}
					</div>
					<div class="item" @click="changePageType('rePassword')">
						<el-select class="select" :class="currLanguage" v-model="more" :placeholder="$t('更多选项')"
							width="100px" @change="change" style="background-color: none;">
							<el-option v-for="item in options" :key="item.value" :label="$t(item.label)"
								:value="item.value">
							</el-option>
						</el-select>
					</div>
				</div>
			</el-form>
		</div>


		<div class="login-content rePassword drag-box" :class="currLanguage" v-show="pageType == 'rePassword'">
			<dragBar login></dragBar>

			<div class="login-brand">
				<img class="logo" src="../../public/logo.png" />
				<!-- <div>登录Shannon</div> -->
			</div>

			<el-form class="login-form rePassword drag-box-none" :model="rePasswordForm" status-icon
				:rules="rulesRepassword" ref="rePasswordForm" @keyup.enter.native="submitForm('rePasswordForm')"
				label-position="left">


				<div class="loginType">
					<div class="item" v-if="false">
						{{ $t('手机号注册') }}
					</div>
					<div class="item" :class="{ on: loginType == '2' }">
						{{ $t('找回密码') }}
					</div>
				</div>

				<el-form-item label="" prop="terminal" v-show="false">
					<el-input type="terminal" v-model="rePasswordForm.terminal" autocomplete="off"></el-input>
				</el-form-item>

				<el-form-item label="" prop="email">
					<el-input type="email" v-model="rePasswordForm.email" autocomplete="off" :placeholder="$t('邮箱')">
						<el-button slot="append" @click="code">{{ $t(text) }}</el-button>
					</el-input>
				</el-form-item>

				<el-form-item label="" prop="captcha">
					<el-input type="captcha" v-model="rePasswordForm.captcha" autocomplete="off"
						:placeholder="$t('验证码')"></el-input>
				</el-form-item>

				<el-form-item label="" prop="password">
					<el-input type="password" v-model="rePasswordForm.password" autocomplete="off"
						:placeholder="$t('密码')"></el-input>
				</el-form-item>

				<el-form-item label="" prop="confirmPassword">
					<el-input type="password" v-model="rePasswordForm.confirmPassword" autocomplete="off"
						:placeholder="$t('确认密码')"></el-input>
				</el-form-item>

				<el-form-item class="btn_box">
					<el-button class="fullbtn" type="primary" @click="submitForm('rePasswordForm')">{{ $t('立即找回')
						}}</el-button>
				</el-form-item>

				<div class="register">
					<!-- <router-link to="/register">没有账号,前往注册</router-link> -->
				</div>


				<div class="changeLoginMethod">
					<!-- <div class="item" v-if="loginMethod == 'password'" @click="loginMethod = 'code'">
						验证码登录
					</div>
					<div class="item" v-else @click="loginMethod = 'password'">
						密码登录
					</div> -->

					<div class="item" @click="changePageType('login')">
						{{ $t('返回登录') }}
					</div>
				</div>
			</el-form>
		</div>
		<!-- <icp></icp> -->
	</div>

</template>

<script>
import { resetPassword } from '@/api/userInfo.js'
import { login } from '@/api/login.js'
import { sendCodeEMail, langcodeOption } from '@/api/common.js'
// import Icp from '../components/common/Icp.vue'
import sendVerifyCode from "@/utils/SendVerifyCode";
import {
	Debounce
} from '@/utils/double.js'
import {
	captchaLoginEmail
} from '@/api/login.js'
import dragBar from '@/view/components/dragBar'
import { versionCache } from '../config/app';
import localForage from 'localforage';

export default {
	name: "login",
	mixins: [sendVerifyCode],
	components: {
		dragBar
	},
	data() {
		var checkEmail = (rule, value, callback) => {
			if (!value) {
				return callback(new Error(this.$t('请输入邮箱')));
			}
			callback();
		};
		var checkCaptcha = (rule, value, callback) => {
			if (!value) {
				return callback(new Error(this.$t('请输入验证码')));
			}
			if (value.length != 6) {
				return callback(new Error(this.$t('验证码格式为6位')));

			}
			callback();
		};
		var checkPhone = (rule, value, callback) => {
			if (!value) {
				return callback(new Error(this.$t('请输入用户名')));
			}
			callback();
		};
		var checkPassword = (rule, value, callback) => {
			if (value === '') {
				callback(new Error(this.$t('请输入密码')));
			}
			callback();
		};
		var checkConfirmPassword = (rule, value, callback) => {
			if (value === '') {
				callback(new Error(this.$t('请输入确认密码')));
			}
			if (value != this.rePasswordForm.password) {
				callback(new Error(this.$t('两次输入的密码不一致')));
			}
			callback();
		}
		return {
			language: null,
			languageList: [],

			remember: true,
			appVersion: require('../../package.json').version,  // Import the version from package.json
			options: [{
				value: 'register',
				label: '注册账号'
			}, {
				value: 'rePassword',
				label: '忘记密码'
			}],
			more: '',
			pageType: 'login',
			loginMethod: 'password',
			loginType: '2',

			loginForm: {
				terminal: this.$enums.TERMINAL_TYPE.WEB,
				phone: '',
				password: '',
				email: '',
				captcha: '',
			},
			rePasswordForm: {
				terminal: this.$enums.TERMINAL_TYPE.WEB,
				phone: '',
				password: '',
				email: '',
				captcha: '',
			},
			rules: {
				captcha: [{
					validator: checkCaptcha,
					trigger: 'blur'
				}],
				email: [{
					validator: checkEmail,
					trigger: 'blur'
				}],
				phone: [{
					validator: checkPhone,
					trigger: 'blur'
				}],
				password: [{
					validator: checkPassword,
					trigger: 'blur'
				}]
			},
			rulesRepassword: {
				captcha: [{
					validator: checkCaptcha,
					trigger: 'blur'
				}],
				email: [{
					validator: checkEmail,
					trigger: 'blur'
				}],
				password: [{
					validator: checkPassword,
					trigger: 'blur'
				}],
				confirmPassword: [{
					validator: checkConfirmPassword,
					trigger: 'blur'
				}]
			}
		};
	},
	computed: {
		currLanguage() {
			return localStorage.getItem('locale')
		}
	},
	methods: {
		getOptions() {
			// 语言列表
			langcodeOption().then(data => {
				// console.log(res)
				const languageList = new Array;
				data.forEach(item => {
					languageList.push({
						label: item.languageName,
						value: item.fileName,
					})
				})
				this.languageList = languageList
				// this.values=fanyig.value
				if (languageList.length > 0 && !this.getLanguage) {
					this.language = languageList[0].value;
					if (this.$i18n.locale) this.language = this.$i18n.locale
				}
			})
		},
		change(e) {
			if (e == 'register') {
				this.$router.push("/register");
			}
			this.changePageType(e)
			this.more = this.$t('更多选项')
		},
		changeLanguage(e) {
			this.$changeLanguage(e)
		},
		changePageType(pageType) {
			this.pageType = pageType
			if (pageType == 'login') {
				// this.$refs['loginForm'].resetFields();
				this.$ipcRenderer.send("reset-window", 320, 450);
			} else if (pageType == 'rePassword') {
				if (this.currLanguage == 'en-US') {
					this.$ipcRenderer.send("reset-window", 320, 565);
				} else {
					this.$ipcRenderer.send("reset-window", 320, 525);
				}
				// this.$refs['rePasswordForm'].resetFields();
			}
		},
		codeSendEmail(email) {
			let that = this;
			// 发送验证码
			sendCodeEMail({
				email,
				// 1注册
				mailType: 3
			}).then(res => {
				this.$message.success(this.$t('发送成功'))
				that.sendCode();
			})
				.catch(err => {
					return this.$message.err(err)
				});
		},
		code: Debounce(function () {
			if (this.disabled) return
			let that = this;
			let email = null
			if (this.pageType == 'rePassword') {
				email = that.rePasswordForm.email

			} else if (this.pageType == 'login') {
				email = that.loginForm.email
			}
			if (!email) return this.$message.warning(this.$t('请填写邮箱'))
			this.codeSendEmail(email);
		}),
		submitForm(formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					if (this.loginMethod == 'password' && this.pageType == 'login') {
						// 账号密码登录
						let data = { ...this.loginForm, loginType: this.loginType }
						console.log(data)
						login(data).then(res => {
							// 保存密码到cookie(不安全)
							this.setCookie('phone', this.loginForm.phone);
							this.setCookie('password', this.loginForm.password);
							this.setCookie('loginMethod', this.loginMethod);

							localStorage.setItem('phone', this.loginForm.phone);
							localStorage.setItem('remember', this.remember ? 1 : 0);

							if (this.remember) {
								localStorage.setItem('password', this.loginForm.password);
							} else {
								localStorage.setItem('password', '');
							}
							localStorage.setItem('loginMethod', this.loginMethod);
							// 保存token
							sessionStorage.setItem("accessToken", res.token);
							sessionStorage.setItem("refreshToken", res.refreshToken);
							localStorage.setItem("accessToken", res.token);
							localStorage.setItem("refreshToken", res.refreshToken);
							this.$message.success(this.$t("登录成功"));
							this.$ipcRenderer.send("center-window");
							this.$router.push({ path: '/home/chat', query: { login: 1 } });
						})
					} else if (this.loginMethod == 'code' && this.pageType == 'login') {
						let loginForm = {
							email: this.loginForm.email,
							captcha: this.loginForm.captcha,
							terminal: this.loginForm.terminal, // APP终端
							loginType: this.loginMethod == 'code' ? 2 : 1
						}

						captchaLoginEmail(loginForm).then(res => {
							// 保存密码到cookie(不安全)
							this.setCookie('email', this.loginForm.email);
							this.setCookie('loginMethod', this.loginMethod);

							localStorage.setItem('email', this.loginForm.email);
							localStorage.setItem('loginMethod', this.loginMethod);

							// 保存token
							sessionStorage.setItem("accessToken", res.token);
							sessionStorage.setItem("refreshToken", res.refreshToken);
							localStorage.setItem("accessToken", res.token);
							localStorage.setItem("refreshToken", res.refreshToken);
							this.$message.success(this.$t("登录成功"));
							this.$ipcRenderer.send("center-window");
							this.$router.push({ path: '/home/chat', query: { login: 1 } });
						})
					} else if (this.pageType == 'rePassword') {
						let parameters = {
							captcha: this.rePasswordForm.captcha,
							confirmPassword: this.rePasswordForm.confirmPassword,
							// 手机1邮箱2
							loginType: 2,
							password: this.rePasswordForm.password,
							value: this.rePasswordForm.email
						}

						resetPassword(parameters).then(res => {
							this.$message.success(this.$t("修改成功!请牢记密码"));
						})

						setTimeout(function () {
							this.changePageType('login')
						}, 1000)
					}
				}
			});
		},
		resetForm(formName) {
			this.$refs[formName].resetFields();
		},
		// 获取cookie、
		getCookie(name) {
			let reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
			let arr = document.cookie.match(reg)
			if (arr) {
				return unescape(arr[2]);
			}
			return '';
		},
		// 设置cookie,增加到vue实例方便全局调用
		setCookie(name, value) {
			document.cookie = name + "=" + escape(value);
		}
	},
	mounted() {
		let versionStorage = localStorage.getItem('versionStorage')
		if (!versionStorage || versionCache > versionStorage) {
			// 清理用户缓存
			localForage.clear()
		}

		// 初始化窗口
		this.$ipcRenderer.send("reset-window", 320, 450);
		this.$ipcRenderer.send('center-window')

		// 记住密码、记住账号、记住登录方式
		let remember = localStorage.getItem('remember');
		let phone = localStorage.getItem('phone');
		let email = localStorage.getItem('email');
		let password = localStorage.getItem('password');
		let loginMethod = localStorage.getItem('loginMethod');
		if (loginMethod) this.loginMethod = loginMethod
		this.remember = remember == 1 ? true : false;
		this.loginForm.phone = phone?phone:null
		this.loginForm.email = email?email:null
		this.loginForm.password = password
		this.getOptions()
	}
}
</script>

<style scoped lang="scss">
.loginType {
	display: flex;
	align-items: center;
	justify-content: center;
	margin-top: 30px;
	margin-bottom: 40px;

	.item {
		margin: 0 24px;
		// font-weight: bold;
		color: #e2e2e2;
		font-size: 30px;

		&.on {
			color: #000;
		}
	}
}

.changeLoginMethod {
	display: flex;
	padding: 10px;
	font-size: 12px;
	justify-content: center;

	.item {
		cursor: pointer;
		font-size: 14px;
		color: #255F46;
		padding: 0 15px;
		height: 40px;
		line-height: 40px;
		position: relative;

		&::before {
			content: '';
			position: absolute;
			right: 0;
			top: 50%;
			transform: translateY(-50%);
			height: 15px;
			width: 1px;
			background-color: #255F46;
		}

		&:nth-last-child(1)::before {
			content: unset;
		}

		.select {
			width: 100px;
			height: 20px;

			&.en-US {
				width: 150px;
			}

			::v-deep .el-input {
				input {
					background-color: transparent;
					border: none;
					color: #255F46;

					&::placeholder {
						color: #255F46;
					}
				}
			}
		}
	}

}

.login-view {
	width: 100%;
	height: 100%;
	// background: #E8F2FF;
	background-size: cover;
	box-sizing: border-box;
	display: flex;
	justify-content: center;
	align-items: center;

	.back_box {
		position: absolute;
		bottom: 0;
		right: 0;

		.version_box {
			text-align: right;
			color: #999;
			padding: 5px;
			position: absolute;
			bottom: 0;
			right: 0;
		}

		.img {
			width: 100%;
			height: 100%;
			object-fit: contain;
		}


	}

	.login-content {
		position: relative;
		display: flex;
		// align-items: center;
		// height: 100%;
		// background-color: #fff;
		flex-direction: column;
		padding: 15px;
		justify-content: flex-start;
		width: 100%;
		max-width: 320px;
		height: 450px;

		&.rePassword {
			height: 525px;
		}

		&.rePassword.en-US {
			height: 565px;
		}


		.language_box {
			position: absolute;
			top: 40px;
			right: 15px;
			z-index: 2;
			width: 100px;
			height: 20px;

			::v-deep .el-input {
				input {
					background-color: transparent;
					border: none;
					color: #255F46;

					&::placeholder {
						color: #255F46;
					}
				}
			}
		}

		.login-brand {
			display: flex;
			align-items: center;
			line-height: 50px;
			// margin: 20px 0;
			font-size: 22px;
			font-weight: 600;
			letter-spacing: 2px;
			// text-transform: uppercase;
			text-align: center;
			justify-content: flex-start;
			flex-shrink: 0;

			.logo {
				width: 50px;
				height: 50px;
				object-fit: contain;
				// margin-right: 10px;
			}
		}

		.login-form {
			// height: 400px;
			width: 100%;
			// background: white;
			opacity: 0.9;
			// box-shadow: 0px 0px 1px #ccc;
			// border-radius: 3%;
			overflow: hidden;
			// border: 1px solid #ccc;






			.register {
				display: flex;
				flex-direction: row-reverse;
				line-height: 40px;
				text-align: left;
				padding-left: 20px;
			}

			.btn_box {
				.fullbtn {
					width: 100%;
					height: 40px;
				}
			}
		}
	}
}
</style>